<?php
/**
 * @Name: UserLogic.php
 * @Author: yashuai<1762910894@qq.com>
 */

namespace App\Http\Logic\Rbac;

use App\Http\Logic\BaseLogic;
use App\Http\Model\Rbac\UserModel;
use App\Http\Model\Rbac\UserRoleModel;
use HugCode\PhpUnits\CipherText\Password;
use HugCode\PhpUnits\Frame\Code\ConstCode;

class UserLogic extends BaseLogic
{

    /**
     * @Desc 添加用户
     * @tips 需要事务
     * @return int
     * @throws \App\Exceptions\ThrowException
     * @author yashuai<1762910894@qq.com>
     */
    public function create()
    {
        $info = UserModel::getInfo($this->params['UserName'], 'UserName');
        if (!empty($info)) {
            _throw('当前用户名已存在', 106003);
        }
        $this->params['UserID'] = UserModel::newInsert($this->getParamsTableData());
        if (_array_field($this->params, 'RoleID')) {
            UserRoleLogic::instance($this->params)->setUserRole();
        }
        return $this->params['UserID'];
    }

    /**
     * @Desc 编辑
     * @tips 需要事务
     * @return int
     * @throws \App\Exceptions\ThrowException
     * @author yashuai<1762910894@qq.com>
     */
    public function update()
    {
        $info = UserModel::query()->where([
            ['UserName', '=', $this->params['UserName']],
            ['UserID', '<>', $this->params['UserID']]
        ])->first();
        if (!empty($info)) {
            _throw('当前用户名已存在', 106003);
        }
        UserModel::userExist($this->params['UserID'], true);
        $data   = $this->getParamsTableData();
        $result = UserModel::query()->where(['UserID' => $this->params['UserID']])->update($data);
        if (_array_field($this->params, 'RoleID')) {
            UserRoleLogic::instance($this->params)->setUserRole();
        }
        return $result;
    }

    /**
     * @Desc 删除
     * @return int
     * @throws \App\Exceptions\ThrowException
     * @author yashuai<1762910894@qq.com>
     */
    public function status()
    {
        if ($this->params['Status'] == ConstCode::BASIC_STATUS_DELETE) {
            $info = UserModel::userExist($this->params['ID']);
            if ($info['IsSuper'] == 1) {
                _throw('超级管理员不能删除', 106001);
            }
        }
        return UserModel::query()->where(['UserID' => $this->params['ID']])->update([
            'UserStatus' => $this->params['Status']
        ]);
    }

    /**
     * @Desc 获取用户信息
     * @return array|\Illuminate\Database\Query\Builder|mixed
     * @throws \App\Exceptions\ThrowException
     * @author yashuai<1762910894@qq.com>
     */
    public function info()
    {
        $select        = [
            'UserID', 'UserName', 'NickName', 'UserStatus', 'IsSuper'
        ];
        $info          = UserModel::userExist($this->params['UserID'], true, $select);
        $info['roles'] = UserRoleModel::query()->where('UserID', $this->params['UserID'])->pluck('RoleID');
        $node          = NodeLogic::instance($this->params)->getUserNode(true);
        foreach ($node as $val) {
            $info['authorities'][] = [
                'authority' => $val['ControllerName'] . ':' . $val['ActionName'],
                'title'     => $val['title']
            ];
        }

        $info['fileHost'] = env('STATIC_HOST', '');
        $info['webHost']  = env('WEB_HOST', '');
        return $info;
    }

    /**
     * @Desc 数据转为表结构数据
     * @return array
     * @author yashuai<1762910894@qq.com>
     */
    private function getParamsTableData()
    {
        $data = [
            'UserName' => $this->params['UserName'],
            'NickName' => $this->params['NickName'],
        ];
        if (_array_field($this->params, 'UserPassword')) {
            $data['UserPassword'] = Password::generatePassword($this->params['UserPassword']);
        }
        return $this->paramsIssetTableData(['UserEmail', 'IsSuper', 'UserStatus'], $data);
    }

    /**
     * @Desc 修改密码
     * @return int
     * @throws \App\Exceptions\ThrowException
     * @author yashuai<1762910894@qq.com>
     */
    public function resetPassword()
    {
        $info = UserModel::userExist($this->params['UserID'], true, ['UserPassword', 'UserStatus']);
        if (
            _array_field($this->params, 'IsMy') &&
            !empty($info['UserPassword']) &&
            !Password::validatePassword($this->params['OriginalPassword'], $info['UserPassword'])
        ) {
            _throw('原始密码错误', 107002);
        }
        return UserModel::query()->where(['UserID' => $this->params['UserID']])->update([
            'UserPassword' => Password::generatePassword($this->params['UserPassword'])
        ]);
    }

}
